package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.result.Result;
import com.example.common.result.YiFeiException;
import com.example.controller.ZnxController;
import com.example.entity.dto.PurchaseOrder.PurchaseDetailDto;
import com.example.entity.dto.PurchaseOrder.PurtcListAddDto;
import com.example.entity.dto.PurchaseOrder.PurtdListDto;
import com.example.entity.hz.Znx;
import com.example.entity.vo.PurchaseOrder.PurchaseDetailVo;
import com.example.entity.yifei.*;
import com.example.exception.BaseException;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.service.CmsmqService;
import com.example.service.IActFlowCustomService;
import com.example.service.PurtcService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.untils.BeanUtils;
import com.example.untils.NumUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-02-19
 */
@Service
public class PurtcServiceImpl extends ServiceImpl<PurtcMapper, Purtc> implements PurtcService, IActFlowCustomService {

    @Resource
    private CmsmvMapper cmsmvMapper;
    @Resource
    private CmsmeMapper cmsmeMapper;
    @Resource
    private AdmmfMapper admmfMapper;
    @Resource
    private PurmaMapper purmaMapper;
    @Resource
    private PurtaMapper purtaMapper;

    @Resource
    private PurtbMapper purtbMapper;

    @Resource
    private PurtcMapper purtcMapper;

    @Resource
    private PurtdMapper purtdMapper;

    @Resource
    private PurtrMapper purtrMapper;

    @Resource
    private InvmbMapper invmbMapper;

    @Autowired
    private CmsmqService cmsmqService;

    @Autowired
    private PurcdMapper purcdMapper;

    @Autowired
    private CgdzjbMapper cgdzjbMapper;   // 采购单中间表

    @Resource
    private InvmdMapper invmdMapper;

    @Transactional
    public Result add3(PurchaseDetailDto purchaseDetailDto, Purtc old) {
        /**
         *  PurchaseDetailDto purchaseDetailDto
         */
        String res = "";

        if (purchaseDetailDto.getPurtdList().size() == 0) {
            return Result.error("单身没有数据");
        }

        // 单别
        String singleNo = purchaseDetailDto.getTC001();

        String creator = purchaseDetailDto.getCreator();

        // 用户信息表
        Admmf admmf = admmfMapper.selectOne(new QueryWrapper<Admmf>().eq("MF001", creator));
        // 用户分组ID
        String usrGroup = admmf.getMf004();

//        String time = TimeUtils.getNowTime().substring(0, 8);

        Purtc purtc = new Purtc();
        // 生成最新的单号   singleNo(采购单别)
        // TODO CMSMQ表有对每个单据性质的具体编号要求  MQ004 - MQ007
//            String tc002 = purtcMapper.generateTc002(singleNo);
        String tc002 = purchaseDetailDto.getTC002();

        // 供应商基本信息
        Purma purma = purmaMapper.
                selectOne(new QueryWrapper<Purma>().eq("MA001", purchaseDetailDto.getTC004()));

        purtc.setCompany(old.getCompany());
        purtc.setCreator(old.getCreator());
        purtc.setUsrGroup(old.getUsrGroup());
        purtc.setCreateDate(old.getCreateDate());
        if (old.getIdentifier()==1){
            purtc.setModifier(old.getCreator());
            purtc.setUdf12(old.getUdf12());
            purtc.setUdf11(old.getUdf11());
            purtc.setModiDate(TimeUtils.getNowTime());
        }
        purtc.setFlag(1D);

        purtc.setTc001(singleNo);
        purtc.setTc002(tc002);
        purtc.setTc003(purchaseDetailDto.getTC003());
        purtc.setTc004(purchaseDetailDto.getTC004());
        purtc.setTc005(purchaseDetailDto.getTC005());
        purtc.setTc006(purchaseDetailDto.getTC006());   // 汇率
        purtc.setTc007(purma.getMa026());
        purtc.setTc008(purchaseDetailDto.getTC008());  // 付款条件
        purtc.setTc009(purchaseDetailDto.getTC009());
        // 设置工厂编号 宏竹默认是01
        purtc.setTc010("01");    //
        purtc.setTc011(purchaseDetailDto.getTC011());
        purtc.setTc012("1");
        purtc.setTc013(purchaseDetailDto.getTC013());
        purtc.setTc014("N");   // 核审码
        purtc.setTc015("");
        purtc.setTc016("");
        purtc.setTc017("");
        purtc.setTc018(purchaseDetailDto.getTC018());
        purtc.setTc019(purchaseDetailDto.getTC019());
        purtc.setTc020(purchaseDetailDto.getTC020());

        purtc.setUdf52(purchaseDetailDto.getTC019());
        purtc.setUdf53(purchaseDetailDto.getTC020());

        purtc.setTc021(purchaseDetailDto.getTC021());
        purtc.setTc022(purchaseDetailDto.getTC022());
        purtc.setTc023(purchaseDetailDto.getTC023());
        purtc.setTc024(old.getTc024());
        purtc.setTc025("");
        purtc.setTc026(purchaseDetailDto.getTC026());
        purtc.setTc027(purchaseDetailDto.getTC027());
        purtc.setTc028(purchaseDetailDto.getTC028());
        purtc.setTc029(purchaseDetailDto.getTC029());
        purtc.setTc030("0");   // 签核状态码
        purtc.setTc031(0.0);
        purtc.setTc032("");
        purtc.setTc033("N");
        purtc.setTc034("");
        purtc.setTc035("N");
        purtc.setTc036("");
        purtc.setTc037("");
        purtc.setTc038(0.0);
        purtc.setTc039(0.0);
        purtc.setTc040(0.0);
        purtc.setTc041("");
        purtc.setTc042("");
        purtc.setTc043("0");
        purtc.setTc044(purchaseDetailDto.getTC044());
        purtc.setTc045(purchaseDetailDto.getTC045());
        purtc.setTc046("");
        purtc.setTc047("********************");
        purtc.setTcd01("N");
        purtc.setUdf03(purchaseDetailDto.getUDF03());  // 金额合计 (采购金额合计)

        purtcMapper.insert(purtc);

        List<PurtdListDto> purtdList = purchaseDetailDto.getPurtdList();

        int xh = 1;
        // 生成采购单单身
        for (PurtdListDto purtdDto : purtdList) {
//                Purtb purtb = null;
//                // 查询请购单单身
//                if(StringUtils.isNotEmpty(purtdDto.getPurtbSummary()))
//                {
//                    purtb = purtbMapper.selectOne(new QueryWrapper<Purtb>().
//                            eq("TB001", requisitionPurchaseVo.getRequisitionType()).
//                            eq("TB002", requisitionPurchaseVo.getRequisitionNo()).
//                            eq("TB003", requisitionPurchaseVo.getRequisitionNumber()));
//                }
//                // 查询品号信息
            Invmb invmb = invmbMapper.selectOne(new QueryWrapper<Invmb>().
                    eq("MB001", purtdDto.getTD004()));
            if(invmb == null) {
                throw new CustomException("500", "品号不存在");
            }
            Purtd purtd = new Purtd();

            if(purtdDto.getMB039()!=null&&purtdDto.getRestockTime()!=null){
                if (purtdDto.getMB039()!=0&&purtdDto.getRestockTime()!=0) {
                    if (purtdDto.getUnits().equals(purtdDto.getTD009()) && purtdDto.getTD038().equals(purtdDto.getTD009())) {
                        Double test = NumUtils.test(purtdDto.getTD008(), 1.0, purtdDto.getMB039(), purtdDto.getRestockTime());
                        double number = test / 1.0;
                        double aa;
                        if (number == Math.floor(number)) {
                            // 变量为整数
                            aa = number;
                        } else {
                            // 变量不是整数
                            aa = (double) Math.ceil(number);
                        }
                        purtd.setUdf51(aa);
                    } else {
                        // 采购单位换算
                        Invmd invmd = this.invmdMapper.selectOne(new LambdaQueryWrapper<Invmd>().eq(Invmd::getMD001, purtdDto.getTD004()).eq(Invmd::getMD002, purtdDto.getUnits()));
                        if (invmd != null) {
                            //                        System.out.println("请购单号"+arr.getRequisitionNo()+",采购数量:"+arr.getPurchased());
                            Double test = NumUtils.test(purtdDto.getTD008(), invmd.getMD004().doubleValue(), purtdDto.getMB039(), purtdDto.getRestockTime());
                            double number = test / invmd.getMD004().doubleValue();
                            double aa;
                            if (number == Math.floor(number)) {
                                // 变量为整数
                                aa = number;
                            } else {
                                // 变量不是整数
                                aa = (double) Math.ceil(number);
                            }
                            purtd.setUdf51(aa);
                        }
                    }
                }
            }
            purtd.setCompany(purma.getCompany());
            purtd.setCreator(old.getCreator());
            purtd.setUsrGroup(old.getUsrGroup());
            purtd.setCreateDate(old.getCreateDate());
            if (purtdDto.getIdentifier()==1){
                purtd.setModifier(old.getCreator());
                purtd.setModiDate(TimeUtils.getNowTime());
                purtd.setUdf11(purtdDto.getUDF11());
                purtd.setUdf12(purtdDto.getUDF12());
            }
            purtd.setUdf12(purtdDto.getUDF12());
            purtd.setFlag(1D);

            purtd.setTd001(singleNo);
            purtd.setTd002(tc002);
            purtd.setTd003(String.format("%04d", xh));
            xh++;
            // 品号, 品名, 规格
            purtd.setTd004(purtdDto.getTD004());
            purtd.setTd005(purtdDto.getTD005());
            purtd.setTd006(purtdDto.getTD006());
            purtd.setTd007(invmb.getMb017());   // getMb017 主交货仓库

            purtd.setTd008(purtdDto.getTD008());  // 采购数量
            purtd.setTd009(purtdDto.getTD009());   // 单位
            purtd.setTd010(purtdDto.getTD010());   // 采购单价
            purtd.setTd011(purtdDto.getTD011());   // 采购金额

            purtd.setUdf54(purtdDto.getTD011());

            purtd.setTd012(purtdDto.getTD012());               // 预交货日[FORMATE:YMD]

            purtd.setTd015(0.0);
            purtd.setTd016("N");   // 结束码
            purtd.setTd017("");     // 制造商
            purtd.setTd018("N");   // 审核码
            purtd.setTd019(0.0);
            purtd.setTd020("");

            purtd.setTd025(purtdDto.getTD025());  // 急料
            purtd.setTd029("");
            purtd.setTd030(0.0);
            purtd.setTd031(0.0);
            purtd.setTd032("");
            // TODO 这个应该是读用户传入的 ?
            purtd.setTd033(purtdDto.getTD033());    // 税率
            purtd.setTd034(purtdDto.getTD034());    // 税前金额

            purtd.setUdf52(purtdDto.getTD034());

            purtd.setTd035(purtdDto.getTD035());    // 税额

            purtd.setUdf53(purtdDto.getTD035());

            purtd.setTd036(0.0);
            purtd.setTd037(0.0);

            purtd.setTd038(purtdDto.getTD038());   // 计价单位
            System.out.println("计价数量:"+purtdDto.getTD039());
            purtd.setTd039(purtdDto.getTD039());   // 计价数量
            purtd.setTd040("");
            purtd.setTd041("");
            purtd.setTd042("");
            purtd.setTd043("");
            purtd.setTd044("");
            purtd.setTd045(0.0);
            purtd.setTd046(0.0);
            purtd.setTd047(0.0);
            purtd.setTd048(0.0);
            purtd.setTd049(0.0);
            purtd.setTdc01(0.0);
            purtd.setTdc02(0.0);
            purtd.setTdc03("2");
            purtd.setTdc04(0.0);
            purtd.setTdc05(0.0);
            purtd.setTdc06(0.0);
            purtd.setTd050("");
            purtd.setTd051("");
            // 货号
//                purtd.setUdf01(invmb.getUdf01());
            String purtbSummary = purtdDto.getPurtbSummary();

            purtd.setUdf07(purtdDto.getUDF07());
            // 如果不是请购单转过来的
            if(StringUtils.isEmpty(purtbSummary)) {
                purtdMapper.insert(purtd);
                continue;
            }

//                // 拆分请购单身 TB001-TB002-TB003,TB001-TB002-TB003
//                String[] purtbs = purtbSummary.split(",");
//                List<String[]> putrbList = new ArrayList<>();
//                for(String str : purtbs) {
//                    String[] strings = str.split("-");
//                    putrbList.add(strings);
//                }

            List<String[]> putrbList = splitPurtbSummary(purtbSummary);

//                // 拆分采购数量   1000,1000,1000
//                String purchaseNumSummary = purtdDto.getPurchaseNumSummary();
//                String[] purchaseNums = purchaseNumSummary.split(",");
//                // 拆分请购单 请购数量
//                String purtbNumSummary = purtdDto.getPurtbNumSummary();
//                String[] purtbNums = purtbNumSummary.split(",");

            // TODO 销售订单的信息怎么合并 ?
            purtd.setTd013(purtdDto.getTD013());  // 来源单别
            purtd.setTd014(purtdDto.getTD014());
            purtd.setTd021(purtdDto.getTD021());   // 来源单号
            purtd.setTd022("********************");   // 项目编号
            purtd.setTd023(purtdDto.getTD023());   // 来源序号
            purtd.setTd024("");

            // 请购单别, 单号, 序号
            purtd.setTd026(putrbList.get(putrbList.size() - 1)[0]);
            purtd.setTd027(putrbList.get(putrbList.size() - 1)[1]);
            purtd.setTd028(putrbList.get(putrbList.size() - 1)[2]);

            // TA004 请购部门  TA012 请购人员
            Set<String> reqDept = new HashSet<>();
            Set<String> reqUser = new HashSet<>();
            for(int i = 0; i < putrbList.size(); i++) {
                String[] stringsArr = putrbList.get(i);
                // 请购单别 单号 序号
                String DB = stringsArr[0];
                String DH = stringsArr[1];
                Purta purta = purtaMapper.selectOne(new LambdaQueryWrapper<Purta>()
                        .eq(Purta::getTa001, DB).eq(Purta::getTa002, DH));
                System.out.println(DB + "--" + DH);
                if(StringUtils.isNotEmpty(purta.getTa004())) {
                    reqDept.add(purta.getTa004());
                }
                if(StringUtils.isNotEmpty(purta.getTa012())) {
                    reqUser.add(purta.getTa012());
                }
            }
            StringBuffer deptIds = new StringBuffer();
            StringBuffer deptNames = new StringBuffer();
            for (String deptId : reqDept) {
                deptIds.append(deptId.trim() + ",");
                Cmsme cmsme = cmsmeMapper.selectOne(new LambdaQueryWrapper<Cmsme>()
                        .eq(Cmsme::getMe001, deptId));
                deptNames.append(cmsme.getMe002().trim() + ",");
            }
            if(deptIds.length() > 0) deptIds.deleteCharAt(deptIds.length() - 1);
            if(deptNames.length() > 0) deptNames.deleteCharAt(deptNames.length() - 1);
            // 请购部门编号
            purtd.setUdf03(deptIds.toString());
            // 请购部门名称
            purtd.setUdf04(deptNames.toString());
            StringBuffer userIds = new StringBuffer();
            StringBuffer userNames = new StringBuffer();
            for (String userId : reqUser) {
                userIds.append(userId.trim() + ",");
                Cmsmv cmsmv = cmsmvMapper.selectOne(new LambdaQueryWrapper<Cmsmv>()
                        .eq(Cmsmv::getMv001, userId));
                userNames.append(cmsmv.getMv002().trim() + ",");
            }
            if(userIds.length() > 0) userIds.deleteCharAt(userIds.length() - 1);
            if(userNames.length() > 0) userNames.deleteCharAt(userNames.length() - 1);
            // 请购人员编号
            purtd.setUdf05(userIds.toString());
            // 请购人员名称
            purtd.setUdf06(userNames.toString());

            // 由哪几张请购单过来
//                purtd.setUdf07(purtbSummary);
//                    if (purtdDto.getMB039()!=0&&purtdDto.getRestockTime()!=0) {
            if (purtdDto.getUnits().equals(purtdDto.getTD009()) && purtdDto.getTD038().equals(purtdDto.getTD009())) {
//                            Double test = NumUtils.test(purtdDto.getTD008(), 1.0, purtdDto.getMB039(), purtdDto.getRestockTime());
                double number = purtdDto.getTD008() * 1.0;
                double aa;
                if (number == Math.floor(number)) {
                    // 变量为整数
                    aa = number;
                } else {
                    // 变量不是整数
                    aa = (double) Math.ceil(number);
                }
                purtd.setUdf51(aa);
                purtdDto.setUdf51(aa);
//                            System.out.println("123456"+aa);
            } else {
                // 采购单位换算
                Invmd invmd = this.invmdMapper.selectOne(new LambdaQueryWrapper<Invmd>().eq(Invmd::getMD001, purtdDto.getTD004()).eq(Invmd::getMD002, purtdDto.getTD009()));
                if (invmd != null) {
//                                System.out.println("000");
                    //                        System.out.println("请购单号"+arr.getRequisitionNo()+",采购数量:"+arr.getPurchased());
//                                Double test = NumUtils.test(purtdDto.getTD008(), invmd.getMD004().doubleValue(), purtdDto.getMB039(), purtdDto.getRestockTime());
                    double number = purtdDto.getTD008() * invmd.getMD004().doubleValue();
                    double aa;
                    if (number == Math.floor(number)) {
                        // 变量为整数
                        aa = number;
                    } else {
                        // 变量不是整数
                        aa = (double) Math.ceil(number);
                    }
                    purtd.setUdf51(aa);
                    purtdDto.setUdf51(aa);
//                                System.out.println("1234567"+aa);
                }
            }
//                    }else {
//                        if (purtdDto.getUnits().equals(purtdDto.getTD009()) && purtdDto.getTD038().equals(purtdDto.getTD009())) {
//                            Double test = NumUtils.test(purtdDto.getTD008(), 1.0, 1.0, 1.0);
//                            double number = test / 1.0;
//                            double aa;
//                            if (number == Math.floor(number)) {
//                                // 变量为整数
//                                aa = number;
//                            } else {
//                                // 变量不是整数
//                                aa = (double) Math.ceil(number);
//                            }
//                            purtd.setUdf51(aa);
//                            purtdDto.setUdf51(aa);
////                            System.out.println("12345678"+aa);
//                        } else {
//                            // 采购单位换算
//                            Invmd invmd = this.invmdMapper.selectOne(new LambdaQueryWrapper<Invmd>().eq(Invmd::getMD001, purtdDto.getTD004()).eq(Invmd::getMD002, purtdDto.getTD009()));
//                            if (invmd != null) {
//                                //                        System.out.println("请购单号"+arr.getRequisitionNo()+",采购数量:"+arr.getPurchased());
//                                Double test = NumUtils.test(purtdDto.getTD008(), invmd.getMD004().doubleValue(),1.0,1.0);
//                                double number = test / invmd.getMD004().doubleValue();
//                                double aa;
//                                if (number == Math.floor(number)) {
//                                    // 变量为整数
//                                    aa = number;
//                                } else {
//                                    // 变量不是整数
//                                    aa = (double) Math.ceil(number);
//                                }
//                                purtd.setUdf51(aa);
//                                purtdDto.setUdf51(aa);
////                                System.out.println("123456789"+aa);
//                            }
//                        }
//                    }

            purtdMapper.insert(purtd);

            // 计算一共有多少需要用掉的
            double allSum = purtd.getTd008();
            // 写入中间表

            int idx = 0;
            for(idx = 0; idx < putrbList.size(); idx++) {

                String[] stringsArr = putrbList.get(idx);
                // 请购单别 单号 序号
                String DB = stringsArr[0];
                String DH = stringsArr[1];
                String XH = stringsArr[2];

                // 生成单身的时候需要回写到 PURTR 首先删除所有采购码为空的N PURTR
                QueryWrapper<Purtr> purtrQueryWrapper = new QueryWrapper<>();
                purtrQueryWrapper.eq("TR001", DB).
                        eq("TR002", DH).
                        eq("TR003", XH);

                List<Purtr> purtrList = purtrMapper.selectList(purtrQueryWrapper);
                for (Purtr purtr : purtrList) {
//                    System.out.println("delete purtr" + purtr.getTr017());
                    if (purtr.getTr017().equals("N")) {

                        QueryWrapper<Purtr> deleteQueryWrapper = new QueryWrapper<>();
                        deleteQueryWrapper.eq("TR001", DB).
                                eq("TR002", DH).
                                eq("TR003", XH).
                                eq("TR004", purtr.getTr004());
                        purtrMapper.delete(deleteQueryWrapper);
                    }
                }

                // 查询出对应的请购单单身  查出剩余多少数量
                Purtb purtb = purtbMapper.selectOne(new LambdaQueryWrapper<Purtb>().
                        eq(Purtb::getTb001, DB).eq(Purtb::getTb002, DH).eq(Purtb::getTb003, XH));

                if(allSum <= 0) break;
                double needToBuy = 0;
                if(idx == putrbList.size() - 1) {   // 特判一下最后一单的话, 需要全部的都算在后面
                    needToBuy = allSum;
                }else{
                    needToBuy = purtb.getTb048();
                }
                allSum -= needToBuy;

                Purtr purtr = new Purtr();
                purtr.setCompany(purma.getCompany());
                purtr.setCreator(creator);
                purtr.setUsrGroup(usrGroup);
                purtr.setCreateDate(TimeUtils.getNowTime());
                purtr.setModifier(creator);
                purtr.setModiDate(TimeUtils.getNowTime());
                purtr.setFlag(new Double(1));

                purtr.setTr001(DB);
                purtr.setTr002(DH);
                purtr.setTr003(XH);

                String serialNumber = purtrMapper.selectCountTr004(DB, DH, XH);
//                    System.out.println(serialNumber);
                purtr.setTr004(String.format("%04d", Integer.parseInt(serialNumber.trim())));
                purtr.setTr005(purchaseDetailDto.getTC004());
                purtr.setTr007(needToBuy / purtb.getTb014());  // 采购比率
                // TODO 采购数量   采购单位 ???
                purtr.setTr006(needToBuy);
                purtr.setTr008(purtdDto.getTD009());
                // 采购币种  单价  金额
                purtr.setTr009(purtc.getTc005());
                purtr.setTr010(purtd.getTd010());
                purtr.setTr011(purtd.getTd011());
                purtr.setTr012(purtc.getTc018());     // 税种
                purtr.setTr013(purtdDto.getTD012());  // 交货日
                // ?
                purtr.setTr014(invmb.getMb017());    // 交货仓库
                purtr.setTr015(purtd.getTd025());   // 急料
                purtr.setTr016(purtd.getTd014());   // 备注
                purtr.setTr017("Y");
                purtr.setTr018("N");
                // 采购单号
                purtr.setTr019(purtd.getTd001() + "-" + purtd.getTd002() + "-" + purtd.getTd003());
                purtr.setTr020(new Double(0.0));
                purtr.setTr021("");
                purtr.setTr022(new Double(0.0));
                purtr.setTr023(new Double(0.0));
                purtr.setTr024("");
                purtr.setTr025("");   // 信息说明
                purtr.setTr026(purtd.getTd038());  // 计价单位
                purtr.setTr027(needToBuy);
                purtr.setTr028("");
                purtr.setTr029("");
                purtr.setTr030("");
                purtr.setTr031(new Double(0.0));
                purtr.setTr032(new Double(0.0));
                purtr.setTr033(new Double(0.0));
                purtr.setTr034("********************");

                purtrMapper.insert(purtr);
                cgdzjbMapper.insert(new Cgdzjb(purtd.getTd001(), purtd.getTd002(), purtd.getTd003(),
                        purtb.getTb001(), purtb.getTb002(), purtb.getTb003(), purtr.getTr004(), purtdDto.getUdf51(),
                        TimeUtils.getFullNowTime(), TimeUtils.getFullNowTime(), creator, idx + 1));

                String tb039 = "N";
//                    System.out.println(purtb.getTb048());
//                    System.out.println(requisitionPurchaseVo.getNumber());
                // TB048 已请未购数量
                if(purtb.getTb048() <= purtb.getUdf51()+purtdDto.getUdf51())
                    tb039 = "Y";

                purtbMapper.updateByTb001WithTb002WithTb003(DB,DH,XH,
                        tb039,purtb.getTb048()-purtdDto.getUdf51(),purtdDto.getUdf51());
            }
        }
        res += singleNo + "-" + tc002 + ";";

        return Result.success(res);
    }

    @Transactional
    @Async
    @Override
    public CompletableFuture<Result> add2(PurtcListAddDto purtcListAddDto) {
        synchronized (this) {
            String res = "";
            List<PurchaseDetailDto> procureDtoList = purtcListAddDto.getProcureDtoList();
            for (PurchaseDetailDto purchaseDetailDto : procureDtoList) {

                if (purchaseDetailDto.getPurtdList().isEmpty()) continue;

                // 单别
                String singleNo = purchaseDetailDto.getTC001();

                String creator = purchaseDetailDto.getCreator();

                // 用户信息表
                Admmf admmf = admmfMapper.selectOne(new QueryWrapper<Admmf>().eq("MF001", creator));
                // 用户分组ID
                String usrGroup = admmf.getMf004();

                String time = TimeUtils.getNowTime().substring(0, 8);

                Purtc purtc = new Purtc();
                // 生成最新的单号   singleNo(采购单别)
                // TODO CMSMQ表有对每个单据性质的具体编号要求  MQ004 - MQ007
//            String tc002 = purtcMapper.generateTc002(singleNo);
                String tc002 = cmsmqService.getIdByType(singleNo, "purtc");

                // 供应商基本信息
                Purma purma = purmaMapper.
                        selectOne(new QueryWrapper<Purma>().eq("MA001", purchaseDetailDto.getTC004()));

                purtc.setCompany(purma.getCompany());
                purtc.setCreator(creator);
                purtc.setUsrGroup(usrGroup);
                purtc.setCreateDate(TimeUtils.getNowTime());
//            purtc.setModifier(creator); // 新增接口不需要
//            purtc.setModiDate(TimeUtils.getNowTime());
                purtc.setUdf11(purchaseDetailDto.getUDF11());
                purtc.setFlag(1D);

                purtc.setTc001(singleNo);
                purtc.setTc002(tc002);
                purtc.setTc003(purchaseDetailDto.getTC003());
                purtc.setTc004(purchaseDetailDto.getTC004());
                purtc.setTc005(purchaseDetailDto.getTC005());
                purtc.setTc006(purchaseDetailDto.getTC006());   // 汇率
                purtc.setTc007(purma.getMa026());
                purtc.setTc008(purchaseDetailDto.getTC008());  // 付款条件
                purtc.setTc009(purchaseDetailDto.getTC009());
                // 设置工厂编号 宏竹默认是01
                purtc.setTc010("01");    //
                purtc.setTc011(purchaseDetailDto.getTC011());
                purtc.setTc012("1");
                purtc.setTc013(purchaseDetailDto.getTC013());
                purtc.setTc014("N");   // 核审码
                purtc.setTc015("");
                purtc.setTc016("");
                purtc.setTc017("");
                purtc.setTc018(purchaseDetailDto.getTC018());
                purtc.setTc019(purchaseDetailDto.getTC019());
                purtc.setTc020(purchaseDetailDto.getTC020());

                purtc.setUdf52(purchaseDetailDto.getTC019());
                purtc.setUdf53(purchaseDetailDto.getTC020());

                purtc.setTc021(purchaseDetailDto.getTC021());
                purtc.setTc022(purchaseDetailDto.getTC022());
                purtc.setTc023(purchaseDetailDto.getTC023());
                purtc.setTc024(time);
                purtc.setTc025("");
                purtc.setTc026(purchaseDetailDto.getTC026());
                purtc.setTc027(purchaseDetailDto.getTC027());
                purtc.setTc028(purchaseDetailDto.getTC028());
                purtc.setTc029(purchaseDetailDto.getTC029());
                purtc.setTc030("0");   // 审核码
                purtc.setTc031(0.0);
                purtc.setTc032("");
                purtc.setTc033("N");
                purtc.setTc034("");
                purtc.setTc035("N");
                purtc.setTc036("");
                purtc.setTc037("");
                purtc.setTc038(0.0);
                purtc.setTc039(0.0);
                purtc.setTc040(0.0);
                purtc.setTc041("");
                purtc.setTc042("");
                purtc.setTc043("0");
                purtc.setTc044(purchaseDetailDto.getTC044());
                purtc.setTc045(purchaseDetailDto.getTC045());
                purtc.setTc046("");
                purtc.setTc047("********************");
                purtc.setTcd01("N");
                purtc.setUdf03(purchaseDetailDto.getUDF03());  // 金额合计 (采购金额合计)

                purtcMapper.insert(purtc);

                List<PurtdListDto> purtdList = purchaseDetailDto.getPurtdList();

                int xh = 1;
                // 生成采购单单身
                for (PurtdListDto purtdDto : purtdList) {
//                Purtb purtb = null;
//                // 查询请购单单身
//                if(StringUtils.isNotEmpty(purtdDto.getPurtbSummary()))
//                {
//                    purtb = purtbMapper.selectOne(new QueryWrapper<Purtb>().
//                            eq("TB001", requisitionPurchaseVo.getRequisitionType()).
//                            eq("TB002", requisitionPurchaseVo.getRequisitionNo()).
//                            eq("TB003", requisitionPurchaseVo.getRequisitionNumber()));
//                }
//                // 查询品号信息
                    Invmb invmb = invmbMapper.selectOne(new QueryWrapper<Invmb>().
                            eq("MB001", purtdDto.getTD004()));
                    if(invmb == null) {
                        throw new CustomException("500", "品号不存在");
                    }

                    Purtd purtd = new Purtd();

                    purtd.setCompany(purma.getCompany());
                    purtd.setCreator(creator);
                    purtd.setUsrGroup(usrGroup);
                    purtd.setCreateDate(TimeUtils.getNowTime());
                    purtd.setUdf11(purtdDto.getUDF11());
                    purtd.setFlag(1D);

                    purtd.setTd001(singleNo);
                    purtd.setTd002(tc002);
                    purtd.setTd003(String.format("%04d", xh));
                    xh++;
                    // 品号, 品名, 规格
                    purtd.setTd004(purtdDto.getTD004());
                    purtd.setTd005(purtdDto.getTD005());
                    purtd.setTd006(purtdDto.getTD006());
                    purtd.setTd007(invmb.getMb017());   // getMb017 主交货仓库

                    purtd.setTd008(purtdDto.getTD008());  // 采购数量
                    purtd.setTd009(purtdDto.getTD009());   // 单位
                    purtd.setTd010(purtdDto.getTD010());   // 采购单价
                    purtd.setTd011(purtdDto.getTD011());   // 采购金额

                    purtd.setUdf54(purtdDto.getTD011());

                    purtd.setTd012(purtdDto.getTD012());               // 预交货日[FORMATE:YMD]

                    purtd.setTd015(0.0);
                    purtd.setTd016("N");   // 结束码
                    purtd.setTd017("");     // 制造商
                    purtd.setTd018("N");   // 审核码
                    purtd.setTd019(0.0);
                    purtd.setTd020("");

                    purtd.setTd025(purtdDto.getTD025());  // 急料
                    purtd.setTd029("");
                    purtd.setTd030(0.0);
                    purtd.setTd031(0.0);
                    purtd.setTd032("");
                    // TODO 这个应该是读用户传入的 ?
                    purtd.setTd033(purtdDto.getTD033());    // 税率
                    purtd.setTd034(purtdDto.getTD034());    // 税前金额

                    purtd.setUdf52(purtdDto.getTD034());

                    purtd.setTd035(purtdDto.getTD035());    // 税额

                    purtd.setUdf53(purtdDto.getTD035());

                    purtd.setTd036(0.0);
                    purtd.setTd037(0.0);

                    purtd.setTd038(purtdDto.getTD038());   // 计价单位
//                    System.out.println("计价数量:"+purtdDto.getTD039());
                    purtd.setTd039(purtdDto.getTD039());   // 计价数量
                    purtd.setTd040("");
                    purtd.setTd041("");
                    purtd.setTd042("");
                    purtd.setTd043("");
                    purtd.setTd044("");
                    purtd.setTd045(0.0);
                    purtd.setTd046(0.0);
                    purtd.setTd047(0.0);
                    purtd.setTd048(0.0);
                    purtd.setTd049(0.0);
                    purtd.setTdc01(0.0);
                    purtd.setTdc02(0.0);
                    purtd.setTdc03("2");
                    purtd.setTdc04(0.0);
                    purtd.setTdc05(0.0);
                    purtd.setTdc06(0.0);
                    purtd.setTd050("");
                    purtd.setTd051("");
                    // 货号
//                purtd.setUdf01(invmb.getUdf01());
                    String purtbSummary = purtdDto.getPurtbSummary();

                    purtd.setUdf07(purtdDto.getUDF07());
                    // 如果不是请购单转过来的
                    if(StringUtils.isEmpty(purtbSummary)) {
                        purtdMapper.insert(purtd);
                        continue;
                    }

//                // 拆分请购单身 TB001-TB002-TB003,TB001-TB002-TB003
//                String[] purtbs = purtbSummary.split(",");
//                List<String[]> putrbList = new ArrayList<>();
//                for(String str : purtbs) {
//                    String[] strings = str.split("-");
//                    putrbList.add(strings);
//                }

                    List<String[]> putrbList = splitPurtbSummary(purtbSummary);

//                // 拆分采购数量   1000,1000,1000
//                String purchaseNumSummary = purtdDto.getPurchaseNumSummary();
//                String[] purchaseNums = purchaseNumSummary.split(",");
//                // 拆分请购单 请购数量
//                String purtbNumSummary = purtdDto.getPurtbNumSummary();
//                String[] purtbNums = purtbNumSummary.split(",");

                    // TODO 销售订单的信息怎么合并 ?
                    purtd.setTd013(purtdDto.getTD013());  // 来源单别
                    purtd.setTd014(purtdDto.getTD014());
                    purtd.setTd021(purtdDto.getTD021());   // 来源单号
                    purtd.setTd022("********************");   // 项目编号
                    purtd.setTd023(purtdDto.getTD023());   // 来源序号
                    purtd.setTd024("");

                    // 请购单别, 单号, 序号
                    purtd.setTd026(putrbList.get(putrbList.size() - 1)[0]);
                    purtd.setTd027(putrbList.get(putrbList.size() - 1)[1]);
                    purtd.setTd028(putrbList.get(putrbList.size() - 1)[2]);

                    // TA004 请购部门  TA012 请购人员
                    Set<String> reqDept = new HashSet<>();
                    Set<String> reqUser = new HashSet<>();
                    for(int i = 0; i < putrbList.size(); i++) {
                        String[] stringsArr = putrbList.get(i);
                        // 请购单别 单号 序号
                        String DB = stringsArr[0];
                        String DH = stringsArr[1];
                        Purta purta = purtaMapper.selectOne(new LambdaQueryWrapper<Purta>()
                                .eq(Purta::getTa001, DB).eq(Purta::getTa002, DH));

                        if(StringUtils.isNotEmpty(purta.getTa004())) {
                            reqDept.add(purta.getTa004());
                        }
                        if(StringUtils.isNotEmpty(purta.getTa012())) {
                            reqUser.add(purta.getTa012());
                        }
                    }
                    StringBuffer deptIds = new StringBuffer();
                    StringBuffer deptNames = new StringBuffer();
                    for (String deptId : reqDept) {
                        deptIds.append(deptId.trim() + ",");
                        Cmsme cmsme = cmsmeMapper.selectOne(new LambdaQueryWrapper<Cmsme>()
                                .eq(Cmsme::getMe001, deptId));
                        deptNames.append(cmsme.getMe002().trim() + ",");
                    }
                    if(deptIds.length() > 0) deptIds.deleteCharAt(deptIds.length() - 1);
                    if(deptNames.length() > 0) deptNames.deleteCharAt(deptNames.length() - 1);
                    // 请购部门编号
                    purtd.setUdf03(deptIds.toString());
                    // 请购部门名称
                    purtd.setUdf04(deptNames.toString());
                    StringBuffer userIds = new StringBuffer();
                    StringBuffer userNames = new StringBuffer();
                    for (String userId : reqUser) {
                        userIds.append(userId.trim() + ",");
                        Cmsmv cmsmv = cmsmvMapper.selectOne(new LambdaQueryWrapper<Cmsmv>()
                                .eq(Cmsmv::getMv001, userId));
                        userNames.append(cmsmv.getMv002().trim() + ",");
                    }
                    if(userIds.length() > 0) userIds.deleteCharAt(userIds.length() - 1);
                    if(userNames.length() > 0) userNames.deleteCharAt(userNames.length() - 1);
                    // 请购人员编号
                    purtd.setUdf05(userIds.toString());
                    // 请购人员名称
                    purtd.setUdf06(userNames.toString());

                    // 由哪几张请购单过来
//                purtd.setUdf07(purtbSummary);
//                    if (purtdDto.getMB039()!=0&&purtdDto.getRestockTime()!=0) {
                        if (purtdDto.getUnits().equals(purtdDto.getTD009()) && purtdDto.getTD038().equals(purtdDto.getTD009())) {
//                            Double test = NumUtils.test(purtdDto.getTD008(), 1.0, purtdDto.getMB039(), purtdDto.getRestockTime());
                            double number = purtdDto.getTD008() * 1.0;
                            double aa;
                            if (number == Math.floor(number)) {
                                // 变量为整数
                                aa = number;
                            } else {
                                // 变量不是整数
                                aa = (double) Math.ceil(number);
                            }
                            purtd.setUdf51(aa);
                            purtdDto.setUdf51(aa);
//                            System.out.println("123456"+aa);
                        } else {
                            // 采购单位换算
                            Invmd invmd = this.invmdMapper.selectOne(new LambdaQueryWrapper<Invmd>().eq(Invmd::getMD001, purtdDto.getTD004()).eq(Invmd::getMD002, purtdDto.getTD009()));
                            if (invmd != null) {
//                                System.out.println("000");
                                //                        System.out.println("请购单号"+arr.getRequisitionNo()+",采购数量:"+arr.getPurchased());
//                                Double test = NumUtils.test(purtdDto.getTD008(), invmd.getMD004().doubleValue(), purtdDto.getMB039(), purtdDto.getRestockTime());
                                double number = purtdDto.getTD008() * invmd.getMD004().doubleValue();
                                double aa;
                                if (number == Math.floor(number)) {
                                    // 变量为整数
                                    aa = number;
                                } else {
                                    // 变量不是整数
                                    aa = (double) Math.ceil(number);
                                }
                                purtd.setUdf51(aa);
                                purtdDto.setUdf51(aa);
//                                System.out.println("1234567"+aa);
                            }
                        }
//                    }else {
//                        if (purtdDto.getUnits().equals(purtdDto.getTD009()) && purtdDto.getTD038().equals(purtdDto.getTD009())) {
//                            Double test = NumUtils.test(purtdDto.getTD008(), 1.0, 1.0, 1.0);
//                            double number = test / 1.0;
//                            double aa;
//                            if (number == Math.floor(number)) {
//                                // 变量为整数
//                                aa = number;
//                            } else {
//                                // 变量不是整数
//                                aa = (double) Math.ceil(number);
//                            }
//                            purtd.setUdf51(aa);
//                            purtdDto.setUdf51(aa);
////                            System.out.println("12345678"+aa);
//                        } else {
//                            // 采购单位换算
//                            Invmd invmd = this.invmdMapper.selectOne(new LambdaQueryWrapper<Invmd>().eq(Invmd::getMD001, purtdDto.getTD004()).eq(Invmd::getMD002, purtdDto.getTD009()));
//                            if (invmd != null) {
//                                //                        System.out.println("请购单号"+arr.getRequisitionNo()+",采购数量:"+arr.getPurchased());
//                                Double test = NumUtils.test(purtdDto.getTD008(), invmd.getMD004().doubleValue(),1.0,1.0);
//                                double number = test / invmd.getMD004().doubleValue();
//                                double aa;
//                                if (number == Math.floor(number)) {
//                                    // 变量为整数
//                                    aa = number;
//                                } else {
//                                    // 变量不是整数
//                                    aa = (double) Math.ceil(number);
//                                }
//                                purtd.setUdf51(aa);
//                                purtdDto.setUdf51(aa);
////                                System.out.println("123456789"+aa);
//                            }
//                        }
//                    }

                    purtdMapper.insert(purtd);

                    // 计算一共有多少需要用掉的
                    double allSum = purtd.getTd008();
                    // 写入中间表

                    int idx = 0;
                    for(idx = 0; idx < putrbList.size(); idx++) {

                        String[] stringsArr = putrbList.get(idx);
                        // 请购单别 单号 序号
                        String DB = stringsArr[0];
                        String DH = stringsArr[1];
                        String XH = stringsArr[2];

                        // 生成单身的时候需要回写到 PURTR 首先删除所有采购码为空的N PURTR
                        QueryWrapper<Purtr> purtrQueryWrapper = new QueryWrapper<>();
                        purtrQueryWrapper.eq("TR001", DB).
                                eq("TR002", DH).
                                eq("TR003", XH);

                        List<Purtr> purtrList = purtrMapper.selectList(purtrQueryWrapper);
                        for (Purtr purtr : purtrList) {
//                    System.out.println("delete purtr" + purtr.getTr017());
                            if (purtr.getTr017().equals("N")) {

                                QueryWrapper<Purtr> deleteQueryWrapper = new QueryWrapper<>();
                                deleteQueryWrapper.eq("TR001", DB).
                                        eq("TR002", DH).
                                        eq("TR003", XH).
                                        eq("TR004", purtr.getTr004());
                                purtrMapper.delete(deleteQueryWrapper);
                            }
                        }

                        // 查询出对应的请购单单身  查出剩余多少数量
                        Purtb purtb = purtbMapper.selectOne(new LambdaQueryWrapper<Purtb>().
                                eq(Purtb::getTb001, DB).eq(Purtb::getTb002, DH).eq(Purtb::getTb003, XH));

                        if (purtb.getTb039().equals("Y")){
                            throw new YiFeiException(500,"该请购单已数量请购完成,无需再次请购");
                        }

                        if(allSum <= 0) break;
                        double needToBuy = 0;
                        if(idx == putrbList.size() - 1) {   // 特判一下最后一单的话, 需要全部的都算在后面
                            needToBuy = allSum;
                        }else{
                            needToBuy = purtb.getTb048();
                        }
                        allSum -= needToBuy;

                        Purtr purtr = new Purtr();
                        purtr.setCompany(purma.getCompany());
                        purtr.setCreator(creator);
                        purtr.setUsrGroup(usrGroup);
                        purtr.setCreateDate(TimeUtils.getNowTime());
//                    purtr.setModifier(creator);
//                    purtr.setModiDate(TimeUtils.getNowTime());
                        purtr.setFlag(new Double(1));

                        purtr.setTr001(DB);
                        purtr.setTr002(DH);
                        purtr.setTr003(XH);

                        String serialNumber = purtrMapper.selectCountTr004(DB, DH, XH);
//                    System.out.println(serialNumber);
                        purtr.setTr004(String.format("%04d", Integer.parseInt(serialNumber.trim())));
                        purtr.setTr005(purchaseDetailDto.getTC004());
                        purtr.setTr007(needToBuy / purtb.getTb014());  // 采购比率
                        // TODO 采购数量   采购单位 ???
                        purtr.setTr006(needToBuy);
                        purtr.setTr008(purtdDto.getTD009());
                        // 采购币种  单价  金额
                        purtr.setTr009(purtc.getTc005());
                        purtr.setTr010(purtd.getTd010());
                        purtr.setTr011(purtd.getTd011());
                        purtr.setTr012(purtc.getTc018());     // 税种
                        purtr.setTr013(purtdDto.getTD012());  // 交货日
                        // ?
                        purtr.setTr014(invmb.getMb017());    // 交货仓库
                        purtr.setTr015(purtd.getTd025());   // 急料
                        purtr.setTr016(purtd.getTd014());   // 备注
                        purtr.setTr017("Y");
                        purtr.setTr018("N");
                        // 采购单号
                        purtr.setTr019(purtd.getTd001() + "-" + purtd.getTd002() + "-" + purtd.getTd003());
                        purtr.setTr020(new Double(0.0));
                        purtr.setTr021("");
                        purtr.setTr022(new Double(0.0));
                        purtr.setTr023(new Double(0.0));
                        purtr.setTr024("");
                        purtr.setTr025("");   // 信息说明
                        purtr.setTr026(purtd.getTd038());  // 计价单位
                        purtr.setTr027(needToBuy);
                        purtr.setTr028("");
                        purtr.setTr029("");
                        purtr.setTr030("");
                        purtr.setTr031(new Double(0.0));
                        purtr.setTr032(new Double(0.0));
                        purtr.setTr033(new Double(0.0));
                        purtr.setTr034("********************");

                        purtrMapper.insert(purtr);
                        cgdzjbMapper.insert(new Cgdzjb(purtd.getTd001(), purtd.getTd002(), purtd.getTd003(),
                                purtb.getTb001(), purtb.getTb002(), purtb.getTb003(), purtr.getTr004(), purtdDto.getUdf51(),
                                TimeUtils.getFullNowTime(), TimeUtils.getFullNowTime(), creator, idx + 1));

                        String tb039 = "N";
//                    System.out.println(purtb.getTb048());
//                    System.out.println(requisitionPurchaseVo.getNumber());
                        // TB048 已请未购数量
                        if(purtb.getTb048() <= purtb.getUdf51()+purtdDto.getUdf51()){
                            tb039 = "Y";
                        }
//                        System.out.println("单别"+DB+"单号"+DH+"序号"+XH+"回写"+purtdDto.getUdf51());
                        purtbMapper.updateByTb001WithTb002WithTb003(DB,DH,XH,
                                tb039,purtb.getTb048()-purtdDto.getUdf51(),purtb.getUdf51()+purtdDto.getUdf51());
                    }
                }
                res += singleNo + "-" + tc002 + ";";
            }
            return CompletableFuture.completedFuture(Result.success(res));
        }
    }

    private List<String[]> splitPurtbSummary(String purtbSummary) {
        List<String[]> res = new ArrayList<>();
        // 拆分请购单身 TB001-TB002-TB003,TB001-TB002-TB003
        String[] purtbs = purtbSummary.split(",");
        for(String str : purtbs) {
            String[] strings = str.split("-");
            if(strings.length == 4) {
                res.add(new String[]{strings[0], strings[1] + "-" + strings[2], strings[3]});
            }else{
                res.add(strings);
            }
        }
        return res;
    }

    @Override
    public PurchaseDetailVo purchaseDetail(String TC001, String TC002) {
        LambdaQueryWrapper<Purtc> wrapper = new LambdaQueryWrapper<>();
        return purtcMapper.getOnePurtc(TC001, TC002);
    }

    @Override
    @Transactional
    public void delPurtc(String TC001, String TC002) {
        // 是否有下流单据  PURCD
        LambdaQueryWrapper<Purcd> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Purcd::getCd010, TC001)
                .eq(Purcd::getCd011, TC002);
        Integer count = purcdMapper.selectCount(wrapper);
        if(count > 0) {
            throw new CustomException("500", "该单据已有下流单据不能删除");
        }
        LambdaQueryWrapper<Purtd> purtdWrapper = new LambdaQueryWrapper<>();
        purtdWrapper.eq(Purtd::getTd001, TC001).eq(Purtd::getTd002, TC002);

        List<Purtd> purtdList = purtdMapper.selectList(purtdWrapper);
        // 是否关联请购单, 没有关联直接删除单身 else 还需要修改请购单单身和子单身
        for(Purtd purtd : purtdList) {
            List<Cgdzjb> list = cgdzjbMapper.getListByTD(purtd.getTd001(), purtd.getTd002(), purtd.getTd003());
            // 不是请购单过来的
            if(list.size() == 0) {
                purtdMapper.delete(new LambdaQueryWrapper<Purtd>()
                        .eq(Purtd::getTd001, purtd.getTd001())
                        .eq(Purtd::getTd002, purtd.getTd002())
                        .eq(Purtd::getTd003, purtd.getTd003()));
                continue;
            }

            for(Cgdzjb cgdzjb : list) {
                String DB = cgdzjb.getTb001(), DH = cgdzjb.getTb002(), XH = cgdzjb.getTb003(), serial = cgdzjb.getTr004();
                // 修改purtb
                Purtb purtb = purtbMapper.selectOne(new LambdaQueryWrapper<Purtb>().
                        eq(Purtb::getTb001, DB).eq(Purtb::getTb002, DH).eq(Purtb::getTb003, XH));
                Purtr purtr = purtrMapper.selectOne(new LambdaQueryWrapper<Purtr>().
                        eq(Purtr::getTr001, DB).eq(Purtr::getTr002, DH).eq(Purtr::getTr003, XH).
                        eq(Purtr::getTr004, serial));
                String tb039 = "Y";
                if(purtb.getTb048() + purtr.getTr006() > 0) tb039 = "N";
                purtbMapper.updateByTb001WithTb002WithTb003(DB,DH,XH,
                        tb039,purtb.getTb048() + purtr.getTr006(),purtb.getUdf51() - purtr.getTr006());
                purtrMapper.delete(new LambdaQueryWrapper<Purtr>().
                        eq(Purtr::getTr001, DB).eq(Purtr::getTr002, DH).eq(Purtr::getTr003, XH).
                        eq(Purtr::getTr004, serial));
            }
            purtdMapper.delete(new LambdaQueryWrapper<Purtd>()
                    .eq(Purtd::getTd001, purtd.getTd001())
                    .eq(Purtd::getTd002, purtd.getTd002())
                    .eq(Purtd::getTd003, purtd.getTd003()));
            cgdzjbMapper.delete(new LambdaQueryWrapper<Cgdzjb>().eq(Cgdzjb::getTd001, purtd.getTd001())
                    .eq(Cgdzjb::getTd002, purtd.getTd002()).eq(Cgdzjb::getTd003, purtd.getTd003()));
        }
        // 最后删除单头
        purtcMapper.delete(new LambdaQueryWrapper<Purtc>().eq(Purtc::getTc001, TC001).eq(Purtc::getTc002, TC002));
    }

    @Transactional
    @Override
    public Result addOrUpdatePurtd(PurchaseDetailDto purchaseDetailDto) {
        List<PurtdListDto> purtdList = purchaseDetailDto.getPurtdList();
        for(PurtdListDto purtdDto : purtdList) {
            Purma purma = purmaMapper.
                    selectOne(new QueryWrapper<Purma>().eq("MA001", purchaseDetailDto.getTC004()));
            String creator = purchaseDetailDto.getCreator();
            // 用户信息表
            Admmf admmf = admmfMapper.selectOne(new QueryWrapper<Admmf>().eq("MF001", creator));
            // 用户分组ID
            String usrGroup = admmf.getMf004();
//            String time = TimeUtils.getNowTime().substring(0, 8);

            Purtd purtd = new Purtd();
            BeanUtils.copyPropertiesIgnoreCase(purtdDto, purtd);
            purtd.setCompany(purma.getCompany());
            purtd.setCreator(creator);
            purtd.setUsrGroup(usrGroup);
            purtd.setCreateDate(TimeUtils.getNowTime());
            purtd.setUdf11(creator);
            if (purtdDto.getIdentifier()==1){
                purtd.setModifier(creator);
                purtd.setModiDate(TimeUtils.getNowTime());
                purtd.setUdf12(purchaseDetailDto.getUDF12());
            }
            purtd.setFlag(1D);

            purtd.setTd001(purchaseDetailDto.getTC001());
            purtd.setTd002(purchaseDetailDto.getTC002());
            if(purchaseDetailDto.getOperateMethod().equals("add")) {
                purtd.setTd003(String.format("%04d", purtdMapper.generateTd003(purchaseDetailDto.getTC001(), purchaseDetailDto.getTC002())));
            }else{
                purtd.setTd003(purtdDto.getTD003());
            }
            purtd.setTd011(purtdDto.getTD011());

            purtd.setUdf54(purtdDto.getTD011());
            purtd.setUdf52(purtdDto.getTD034());
            purtd.setUdf53(purtdDto.getTD035());

            purtd.setTd015(0.0);
            purtd.setTd016("N");   // 结束码
            purtd.setTd017("");     // 制造商
            purtd.setTd018("N");   // 审核码
            purtd.setTd019(0.0);
            purtd.setTd020("");

            purtd.setTd025("N");
            purtd.setTd029("");
            purtd.setTd030(0.0);
            purtd.setTd031(0.0);
            purtd.setTd032("");
            purtd.setTd038(purtd.getTd009());   // 计价单位
            purtd.setTd039(purtd.getTd008());   // 计价数量
            purtd.setTdc03("2");

            // 请购单是前端传的，之后按照顺序进行使用  存到中间表中
            if(StringUtils.isEmpty(purtdDto.getPurtbSummary())) {
                if(purchaseDetailDto.getOperateMethod().equals("add")) {
                    purtdMapper.insert(purtd);
                }else{
                    purtdMapper.update(purtd, new LambdaQueryWrapper<Purtd>()
                            .eq(Purtd::getTd001, purtd.getTd001()).eq(Purtd::getTd002, purtd.getTd002())
                            .eq(Purtd::getTd003, purtdDto.getTD003()));
                }
                continue;
            }

            // 拆分请购单身 TB001-TB002-TB003,TB001-TB002-TB003
//            String[] purtbs = purtdDto.getPurtbSummary().split(",");
//            List<String[]> putrbList = new ArrayList<>();
//            for(String str : purtbs) {
//                String[] strings = str.split("-");
//                putrbList.add(strings);
//            }
            List<String[]> putrbList = splitPurtbSummary(purtdDto.getPurtbSummary());
//            // 拆分采购数量   1000,1000,1000
//            String purchaseNumSummary = purtdDto.getPurchaseNumSummary();
//            String[] purchaseNums = purchaseNumSummary.split(",");
//            // 拆分请购单 请购数量
//            String purtbNumSummary = purtdDto.getPurtbNumSummary();
//            String[] purtbNums = purtbNumSummary.split(",");

            // TODO 销售订单的信息怎么合并 ?
            purtd.setTd013(purtdDto.getTD013());  // 来源单别
            purtd.setTd014(purtdDto.getTD014());
            purtd.setTd021(purtdDto.getTD021());   // 来源单号
            purtd.setTd022("********************");   // 项目编号
            purtd.setTd023(purtdDto.getTD023());   // 来源序号
            purtd.setTd024("");   // 计划批号

            // 请购单别, 单号, 序号
            purtd.setTd026(putrbList.get(0)[0]);
            purtd.setTd027(putrbList.get(0)[1]);
            purtd.setTd028(putrbList.get(0)[2]);
            // 由哪几张请购单过来
//            purtd.setUdf07(purtdDto.getPurtbSummary());
            if(purchaseDetailDto.getOperateMethod().equals("add")) {
                purtdMapper.insert(purtd);
            }else{
                purtdMapper.update(purtd, new LambdaQueryWrapper<Purtd>()
                        .eq(Purtd::getTd001, purtd.getTd001()).eq(Purtd::getTd002, purtd.getTd002())
                        .eq(Purtd::getTd003, purtdDto.getTD003()));
            }
            // 计算一共有多少需要用掉的
            double allSum = purtd.getTd008();

            int idx = 0;
            for(idx = 0; idx < putrbList.size(); idx++) {
                String[] stringsArr = putrbList.get(idx);
                // 单别 单号 序号
                String DB = stringsArr[0];
                String DH = stringsArr[1];
                String XH = stringsArr[2];

                // 生成单身的时候需要回写到 PURTR 首先删除所有采购码为空的N PURTR
                QueryWrapper<Purtr> purtrQueryWrapper = new QueryWrapper<>();
                purtrQueryWrapper.eq("TR001", DB).
                        eq("TR002", DH).
                        eq("TR003", XH);

                List<Purtr> purtrList = purtrMapper.selectList(purtrQueryWrapper);
                for (Purtr purtr : purtrList) {
//                    System.out.println("delete purtr" + purtr.getTr017());
                    if (purtr.getTr017().equals("N")) {

                        QueryWrapper<Purtr> deleteQueryWrapper = new QueryWrapper<>();
                        deleteQueryWrapper.eq("TR001", DB).
                                eq("TR002", DH).
                                eq("TR003", XH).
                                eq("TR004", purtr.getTr004());
                        purtrMapper.delete(deleteQueryWrapper);
                    }
                }

                Purtb purtb = purtbMapper.selectOne(new LambdaQueryWrapper<Purtb>().
                        eq(Purtb::getTb001, DB).eq(Purtb::getTb002, DH).eq(Purtb::getTb003, XH));

                double needToBuy = 0;
                boolean flag = false;
                if(allSum < 0) {
                    if(purchaseDetailDto.getOperateMethod().equals("add")) continue;
                    flag = true;
                }else{
                    if(idx == putrbList.size() - 1) {
                        needToBuy = allSum;
                    }else{
                        needToBuy = purtb.getTb048();
                    }
                    allSum -= needToBuy;
                }

                Purtr purtr = new Purtr();
                purtr.setCompany(purma.getCompany());
                purtr.setCreator(creator);
                purtr.setUsrGroup(usrGroup);
                purtr.setCreateDate(TimeUtils.getNowTime());
                purtr.setModifier(creator);
                purtr.setModiDate(TimeUtils.getNowTime());
                purtr.setFlag(new Double(1));

                purtr.setTr001(DB);
                purtr.setTr002(DH);
                purtr.setTr003(XH);

//                    System.out.println(serialNumber);
                /**
                 * 如果是新增操作,就需要添加子序号
                 * update的话,直接不设置。这样更新的时候,相当于不变。
                 * 找唯一记录的话, 需要依靠001, 002, 003 以及 019
                 * 019中的采购单号, 和purtr是一一对应的
                 * 如果是请购单合并的情况。001, 002, 003可以进行区分
                 */
                if(purchaseDetailDto.getOperateMethod().equals("add")) {
                    String serialNumber = purtrMapper.selectCountTr004(DB, DH, XH);
                    purtr.setTr004(String.format("%04d", Integer.parseInt(serialNumber.trim())));
                }
                purtr.setTr005(purchaseDetailDto.getTC004());
                purtr.setTr007(needToBuy / purtb.getTb014());
                // TODO 采购数量   采购单位 ???
                purtr.setTr006(needToBuy);
                purtr.setTr008(purtdDto.getTD009());
                // 采购币种  单价  金额
                purtr.setTr009(purchaseDetailDto.getTC005());
                purtr.setTr010(purtd.getTd010());
                purtr.setTr011(purtd.getTd011());
                purtr.setTr012(purchaseDetailDto.getTC018());   // 税种
                purtr.setTr013(purtdDto.getTD012());  // 交货日
                // ?
                purtr.setTr014(purtd.getTd007());    // 交货仓库
                purtr.setTr015(purtd.getTd025());   // 急料
                purtr.setTr016(purtd.getTd014());   // 备注
                purtr.setTr017("Y");
                purtr.setTr018("N");
                // 采购单号
                purtr.setTr019(purtd.getTd001() + "-" + purtd.getTd002() + "-" + purtd.getTd003());
                purtr.setTr020(new Double(0.0));
                purtr.setTr021("");
                purtr.setTr022(new Double(0.0));
                purtr.setTr023(new Double(0.0));
                purtr.setTr024("");
                purtr.setTr025("");   // 信息说明
                purtr.setTr026(purtd.getTd038());  // 计价单位
                purtr.setTr027(needToBuy);
                purtr.setTr028("");
                purtr.setTr029("");
                purtr.setTr030("");
                purtr.setTr031(new Double(0.0));
                purtr.setTr032(new Double(0.0));
                purtr.setTr033(new Double(0.0));
                purtr.setTr034("********************");

                String tb039 = "N";

                if(purchaseDetailDto.getOperateMethod().equals("add")) {
                    purtrMapper.insert(purtr);
                    if(purtb.getTb048() <= needToBuy)
                        tb039 = "Y";
                    purtbMapper.updateByTb001WithTb002WithTb003(DB,DH,XH,
                            tb039,purtb.getTb048() - needToBuy,purtdDto.getUdf51());
                    cgdzjbMapper.insert(new Cgdzjb(purtd.getTd001(), purtd.getTd002(), purtd.getTd003(),
                            purtb.getTb001(), purtb.getTb002(), purtb.getTb003(), purtr.getTr004(), needToBuy,
                            TimeUtils.getFullNowTime(), TimeUtils.getFullNowTime(), creator, idx + 1));
                }else{  // 如果是update
                    Integer count = cgdzjbMapper.selectCount(new LambdaQueryWrapper<Cgdzjb>().eq(Cgdzjb::getTd001, purtd.getTd001())
                            .eq(Cgdzjb::getTd002, purtd.getTd002()).eq(Cgdzjb::getTd003, purtd.getTd003())
                            .eq(Cgdzjb::getTb001, purtb.getTb001()).eq(Cgdzjb::getTb002, purtb.getTb002())
                            .eq(Cgdzjb::getTb003, purtb.getTb003()));
                    if(count > 1 || count == 0) {
                        throw new RuntimeException("采购单中间表找不到对应数据..");
                    }
                    // 找到老的purtr
                    Purtr oldPurtr = purtrMapper.selectOne(new LambdaQueryWrapper<Purtr>()
                            .eq(Purtr::getTr001, purtr.getTr001()).eq(Purtr::getTr002, purtr.getTr002())
                            .eq(Purtr::getTr003, purtr.getTr003()).eq(Purtr::getTr019, purtr.getTr019()));
                    if(flag) {  // 如果数量少了，需要做删除操作的话
                        purtrMapper.delete(new LambdaQueryWrapper<Purtr>()
                                .eq(Purtr::getTr001, purtr.getTr001()).eq(Purtr::getTr002, purtr.getTr002())
                                .eq(Purtr::getTr003, purtr.getTr003()).eq(Purtr::getTr019, purtr.getTr019()));
                        if(purtb.getTb048() + oldPurtr.getTr006() <= 0)
                            tb039 = "Y";
                        purtbMapper.updateByTb001WithTb002WithTb003(DB,DH,XH,
                                tb039,purtb.getTb048() + oldPurtr.getTr006(),purtb.getUdf51() - oldPurtr.getTr006());
                        // 删除 采购单中间表 cgdzjb
                        cgdzjbMapper.delete(new LambdaQueryWrapper<Cgdzjb>().eq(Cgdzjb::getTd001, purtd.getTd001())
                                .eq(Cgdzjb::getTd002, purtd.getTd002()).eq(Cgdzjb::getTd003, purtd.getTd003())
                                .eq(Cgdzjb::getTb001, purtb.getTb001()).eq(Cgdzjb::getTb002, purtb.getTb002())
                                .eq(Cgdzjb::getTb003, purtb.getTb003()));
                    }else{
                        // 把老的读出来, 才能更新
                        purtrMapper.update(purtr, new LambdaQueryWrapper<Purtr>()
                                .eq(Purtr::getTr001, purtr.getTr001()).eq(Purtr::getTr002, purtr.getTr002())
                                .eq(Purtr::getTr003, purtr.getTr003()).eq(Purtr::getTr019, purtr.getTr019()));
                        // TB048 已请未购数量
                        if(purtb.getTb048() + oldPurtr.getTr006() - purtr.getTr006() <= 0)
                            tb039 = "Y";
                        purtbMapper.updateByTb001WithTb002WithTb003(DB,DH,XH,
                                tb039,purtb.getTb048() + oldPurtr.getTr006() - purtr.getTr006(),purtb.getUdf51() - oldPurtr.getTr006());
                        Cgdzjb cgdzjb = new Cgdzjb();
                        cgdzjb.setNums(needToBuy);
                        cgdzjb.setUpdateTime(TimeUtils.getFullNowTime());
                        cgdzjb.setUser(creator);

                        cgdzjbMapper.update(cgdzjb, new LambdaQueryWrapper<Cgdzjb>().eq(Cgdzjb::getTd001, purtd.getTd001())
                                .eq(Cgdzjb::getTd002, purtd.getTd002()).eq(Cgdzjb::getTd003, purtd.getTd003())
                                .eq(Cgdzjb::getTb001, purtb.getTb001()).eq(Cgdzjb::getTb002, purtb.getTb002())
                                .eq(Cgdzjb::getTb003, purtb.getTb003()));
                    }

                }

            }

        }
        // 修改采购单头
        Purtc purtc = new Purtc();
        BeanUtils.copyPropertiesIgnoreCase(purchaseDetailDto, purtc);
        purtcMapper.update(purtc, new LambdaQueryWrapper<Purtc>()
                .eq(Purtc::getTc001, purtc.getTc001()).eq(Purtc::getTc002, purtc.getTc002()));
        return Result.success("修改成功");
    }

    @Transactional
    @Override
    public Result delPurtd(PurchaseDetailDto purchaseDetailDto) {

        List<PurtdListDto> purtdList = purchaseDetailDto.getPurtdList();
        // 是否关联请购单, 没有关联直接删除单身 else 还需要修改请购单单身和子单身
        for(PurtdListDto purtd : purtdList) {
            List<Cgdzjb> list = cgdzjbMapper.getListByTD(purchaseDetailDto.getTC001(),
                    purchaseDetailDto.getTC002(), purtd.getTD003());
            // 不是请购单过来的
            if(list.size() == 0) {
                purtdMapper.delete(new LambdaQueryWrapper<Purtd>()
                        .eq(Purtd::getTd001, purchaseDetailDto.getTC001())
                        .eq(Purtd::getTd002, purchaseDetailDto.getTC002())
                        .eq(Purtd::getTd003, purtd.getTD003()));
                continue;
            }
            for(Cgdzjb cgdzjb : list) {
                String DB = cgdzjb.getTb001(), DH = cgdzjb.getTb002(), XH = cgdzjb.getTb003(), serial = cgdzjb.getTr004();
                // 修改purtb
                Purtb purtb = purtbMapper.selectOne(new LambdaQueryWrapper<Purtb>().
                        eq(Purtb::getTb001, DB).eq(Purtb::getTb002, DH).eq(Purtb::getTb003, XH));
                Purtr purtr = purtrMapper.selectOne(new LambdaQueryWrapper<Purtr>().
                        eq(Purtr::getTr001, DB).eq(Purtr::getTr002, DH).eq(Purtr::getTr003, XH).
                        eq(Purtr::getTr004, serial));
                String tb039 = "Y";
                if(purtb.getTb048() + purtr.getTr006() > 0) tb039 = "N";
                purtbMapper.updateByTb001WithTb002WithTb003(DB,DH,XH,
                        tb039,purtb.getTb048() + purtr.getTr006(),purtb.getUdf51() - purtr.getTr006());
                purtrMapper.delete(new LambdaQueryWrapper<Purtr>().
                        eq(Purtr::getTr001, DB).eq(Purtr::getTr002, DH).eq(Purtr::getTr003, XH).
                        eq(Purtr::getTr004, serial));
            }
            purtdMapper.delete(new LambdaQueryWrapper<Purtd>()
                    .eq(Purtd::getTd001, purchaseDetailDto.getTC001())
                    .eq(Purtd::getTd002, purchaseDetailDto.getTC002())
                    .eq(Purtd::getTd003, purtd.getTD003()));
            cgdzjbMapper.delete(new LambdaQueryWrapper<Cgdzjb>().eq(Cgdzjb::getTd001, purchaseDetailDto.getTC001())
                    .eq(Cgdzjb::getTd002, purchaseDetailDto.getTC002()).eq(Cgdzjb::getTd003, purtd.getTD003()));
        }
        // 修改采购单头
        Purtc purtc = new Purtc();
        BeanUtils.copyPropertiesIgnoreCase(purchaseDetailDto, purtc);
        purtcMapper.update(purtc, new LambdaQueryWrapper<Purtc>()
                .eq(Purtc::getTc001, purtc.getTc001()).eq(Purtc::getTc002, purtc.getTc002()));
        return Result.success("删除成功");
    }

    @Override
    public Boolean tc30IsN(String tc001, String tc002) {
        PurchaseDetailVo onePurtc = purtcMapper.getOnePurtc(tc001, tc002);
        if (onePurtc!=null&&onePurtc.getTC030().equals("0")){
            return true;
        }
        else {
            throw new BaseException(tc001+"-"+tc002+"该采购单不是未审核采购单");
        }
    }

    @Override
    public Map<String, Object> setvariables(String id, String userName) {
        Map<String,Object> variables = new HashMap<>();
        variables.put("assignee0",userName);
        variables.put("processInsName","采购单流程");
        return variables;
    }

    @Override
    public Map<String, Object> setvariables(String id, String userName, Object vo) {
        Map<String,Object> variables = new HashMap<>();
        variables.put("object",vo);
        variables.put("assignee0",userName);
       /* variables.put("assignee1","rose");
        variables.put("assignee2","mack");
        List<String> group1 = new ArrayList<>();
        group1.add("group1");
        List<String> group2 = new ArrayList<>();
        group2.add("group2");
        variables.put("group1",group1);
        variables.put("group2",group2);*/
        variables.put("processInsName","采购单流程");
        return variables;
    }
    @Override
    public Object taskInfo(Map<String, Object> processVariables) {
        Object object = processVariables.get("object");
        return object;
    }
    /**
     * 流程实例开始时，需要对采购单的操作，例如将采购单的审核状态置为正在审核
     * @param id id是采购单的唯一标识，单别：单头，中间用冒号隔开
     *           例如：123414124：12414123451
     */
    @Override
    public void startRunTask(String id) {
        System.out.printf("采购单审批流程开始业务操作！！！！！id="+id);
        String[] strings = id.split(":");
        Purtc purtc = purtcMapper.selectOne(new LambdaQueryWrapper<Purtc>()
                .eq(Purtc::getTc001, strings[0]).eq(Purtc::getTc002, strings[1]));
        if(purtc == null) {
            throw new CustomException("500", "采购单不存在");
        }
        purtc.setTc030("1"); // 签核中
        purtcMapper.update(purtc, new LambdaQueryWrapper<Purtc>()
                .eq(Purtc::getTc001, strings[0]).eq(Purtc::getTc002, strings[1]));
    }
    @Autowired
private ZnxController znxController;
    /**
     * 流程实例结束时，需要对采购单的操作，例如将采购单的审核状态置为审核通过或审核未通过
     *
     * @param id
     * @param initiator
     */
    @Override
    @Transactional
    public void endRunTask(String id, Boolean state, String defineId, String initiator) {
        System.out.printf("采购单审批流程结束业务操作！！！！！id="+id+"审核状态为："+state);
        String[] strings = id.split(":");
        Purtc purtc = purtcMapper.selectOne(new LambdaQueryWrapper<Purtc>()
                .eq(Purtc::getTc001, strings[0]).eq(Purtc::getTc002, strings[1]));
        if(purtc == null) {
            throw new CustomException("500", "采购单不存在");
        }
        if(state) {  // 审核通过
            purtc.setTc030("3");
            purtcMapper.update(purtc, new LambdaQueryWrapper<Purtc>()
                    .eq(Purtc::getTc001, strings[0]).eq(Purtc::getTc002, strings[1]));
            checkPurtc(strings[0], strings[1]);
            List<Znx> znxList=new ArrayList<>();
            Znx znx=Znx.builder().code(id).content("有一张新的采购单通过了审核!").departmentCode("90807").notificationCode(initiator).customField(defineId)
                    .title("通知").build();
            znxList.add(znx);
            Znx znx2=Znx.builder().code(id).content("有一张新的采购单通过了审核!").departmentCode("90809").customField(defineId)
                    .title("通知").build();
            znxList.add(znx2);
            znxController.insert(znxList);
        }else{  // 审批失败
            purtc.setTc030("2");
            purtcMapper.update(purtc, new LambdaQueryWrapper<Purtc>()
                    .eq(Purtc::getTc001, strings[0]).eq(Purtc::getTc002, strings[1]));
        }
    }

    public void checkPurtc(String TC001, String TC002) {
        if(StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            throw new CustomException("500", "单别或单号为空");
        }
        Purtc purtc = purtcMapper.selectOne(new LambdaQueryWrapper<Purtc>().eq(Purtc::getTc001, TC001).eq(Purtc::getTc002, TC002));
        if(purtc == null) {
            throw new CustomException("500", "单据不存在!");
        }
        purtc.setTc014("Y");
        purtcMapper.update(purtc, new LambdaQueryWrapper<Purtc>().eq(Purtc::getTc001, TC001).eq(Purtc::getTc002, TC002));
        Purtd purtd = new Purtd();
        purtd.setTd018("Y");
        purtdMapper.update(purtd, new LambdaQueryWrapper<Purtd>().eq(Purtd::getTd001, TC001).eq(Purtd::getTd002, TC002));
    }

}
